package com.hxkj.controller.article;

import com.google.code.kaptcha.Producer;
import com.platform.common.domain.exception.CustomMessageException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.imageio.ImageIO;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Random;
import java.util.UUID;

/**
 * created by chenfangzhou on 2018/6/8
 */
@RestController
@RequestMapping("/code")
@SuppressWarnings("all")
public class SendCodeController {

    private static final Logger logger = LoggerFactory.getLogger(SendCodeController.class);
    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private Producer captchaProducer;

    /**
     * 生成验证码
     */
    @RequestMapping(value = "/getcode")
    public void valicode(HttpServletResponse response,HttpServletRequest request) throws Exception {
        /*Cookie[] cookies = request.getCookies();
        for (Cookie cookie_ : cookies){
            if ("COOKIE_NAME_UUID".equals(cookie_.getName())){
                cookie_.setMaxAge(0);
            }
        }*/

        String uuid = UUID.randomUUID().toString().replace("-", "").toLowerCase();
        Cookie cookie = new Cookie("COOKIE_NAME_UUID", uuid);
//		cookie.setMaxAge(10*60*60);
//		cookie.setPath(StringUtils.isBlank(req.getContextPath()) ? "/" : req.getContextPath()+"/");
        cookie.setPath("/");
        cookie.setHttpOnly(true);
//		cookie.setDomain(".imwork.net");
        response.addCookie(cookie);

        try {
            //利用图片工具生成图片
            //第一个参数是生成的验证码，第二个参数是生成的图片
            Object[] objs = createImage();
            //将验证码存入Session
            //将生成的随机字符串保存到Redis中
           // redisTemplate.boundValueOps("checkCodeUUID").set(uuid);
            redisTemplate.boundValueOps(uuid).set(objs[0]);

            //将图片输出给浏览器
            BufferedImage image = (BufferedImage) objs[1];
            response.setContentType("image/png");
            OutputStream os = response.getOutputStream();
            ImageIO.write(image, "png", os);
        } catch (Exception e) {
            logger.error("获取验证码失败>>>>   ", e);
        }

    }


    private static final char[] chars = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9'};
    // 字符数量
    private static final int SIZE = 4;
    // 干扰线数量
    private static final int LINES = 5;
    // 宽度
    private static final int WIDTH = 80;
    // 高度
    private static final int HEIGHT = 40;
    // 字体大小
    private static final int FONT_SIZE = 35;

    /**
     * 生成随机验证码及图片
     * Object[0]：验证码字符串；
     * Object[1]：验证码图片。
     */

    public static Object[] createImage() {
        StringBuffer sb = new StringBuffer();
        // 1.创建空白图片
        BufferedImage image = new BufferedImage(
                WIDTH, HEIGHT, BufferedImage.TYPE_INT_RGB);
        // 2.获取图片画笔
        Graphics graphic = image.getGraphics();
        // 3.设置画笔颜色
        graphic.setColor(Color.LIGHT_GRAY);
        // 4.绘制矩形背景
        graphic.fillRect(0, 0, WIDTH, HEIGHT);
        // 5.画随机字符
        Random ran = new Random();
        for (int i = 0; i < SIZE; i++) {
            // 取随机字符索引
            int n = ran.nextInt(chars.length);
            // 设置随机颜色
            graphic.setColor(getRandomColor());
            // 设置字体大小
            graphic.setFont(new Font(
                    null, Font.BOLD + Font.ITALIC, FONT_SIZE));
            // 画字符
            graphic.drawString(
                    chars[n] + "", i * WIDTH / SIZE, HEIGHT * 4 / 5);
            // 记录字符
            sb.append(chars[n]);
        }
        // 6.画干扰线
        for (int i = 0; i < LINES; i++) {
            // 设置随机颜色
            graphic.setColor(getRandomColor());
            // 随机画线
            graphic.drawLine(ran.nextInt(WIDTH), ran.nextInt(HEIGHT),
                    ran.nextInt(WIDTH), ran.nextInt(HEIGHT));
        }
        // 7.返回验证码和图片
        return new Object[]{sb.toString(), image};
    }
    // 随机取色

    public static Color getRandomColor() {
        Random ran = new Random();
        Color color = new Color(ran.nextInt(256),
                ran.nextInt(256), ran.nextInt(256));
        return color;
    }

    public static void main(String[] args) throws IOException {
        Object[] objs = createImage();
        BufferedImage image = (BufferedImage) objs[1];
        OutputStream os = new FileOutputStream("d:/1.png");
        ImageIO.write(image, "png", os);
        os.close();
    }

}

